<template>
  <div class="g-page-container">
    <PageHeader title="价格变更" />
    <div class="g-content-container">
      <PriceSearchForm ref="search-form" @search="loadTableList" />
      <ButtonGroup :options="buttons" @click="handleButtonClick" />
      <PriceChangeTableList
        :pagination="paginationMixin"
        :loading="loading"
        :data-source="dataSource"
        :row-selection="rowSelectionMixin"
        @change="handleTableChange"
        @number-click="handleNumberClick"
      />
    </div>
    <component
      :is="currentComponent"
      :has-default="hasDefault"
      :visible.sync="visibleDrawer"
      :current-node="currentNode"
      :data="data"
      :logs="logs"
      :key-array="keyArray"
      :price-id="priceId"
      :process-id="processId"
      :form-data.sync="formData"
      :plan-type="planType"
      :has-edit="hasEdit"
      :click-info="clickInfo"
      :curr-status="currStatus"
      :form-info="formInfo"
      :date-arr="dateArr"
      @fresh="loadTableList"
      @change-currstatus="changeCurrstatus"
    />
    <DialogPriceTransferAdmin
      :visible.sync="visibleModal"
      :plan-id="planId"
      :selecteds="selectedInfos"
      number="价格变更编号"
      @fresh="loadTableList"
    />
  </div>
</template>

<script>
import PriceSearchForm from '@/views/price-change/components/PriceSearchForm.vue';
import ButtonGroup from '@/components/button/ButtonGroup.vue';
import DialogPriceTransferAdmin from '@/components/dialog/DialogPriceTransferAdmin .vue';
import mixinTable from '@/mixins/mixin-table.js';
import { PRICE_NODE } from '@/constants/index';

import DrawerPriceStart from './components/DrawerPriceStart.vue';
import PriceChangeTableList from './components/PriceChangeTableList.vue';
import DrawerSalesDirecorAudits from './components/DrawerSalesDirecorAudits.vue';
//

import {
  postPriceList,
  postDeletePriceChange,
  getPriceDetail,
} from '@/api/price.js';
import monent from 'moment';
import { createMonthArray } from '@/utils/time';

export default {
  components: {
    PriceSearchForm,
    ButtonGroup,
    PriceChangeTableList,
    DrawerPriceStart,
    DrawerSalesDirecorAudits,
    DialogPriceTransferAdmin,
  },
  mixins: [mixinTable],
  data() {
    return {
      keyArray: [],
      currentNode: PRICE_NODE[1],
      asc: true,
      columnKey: '',
      loading: false,
      dataSource: [],
      currentComponent: 'DrawerPriceStart',
      visibleDrawer: false,
      clickInfo: {},
      selectedInfos: [],
      visibleModal: false,
      visibleAdd: false,
      data: [],
      priceId: undefined,
      form: {},
      logs: [],
      processId: undefined,
      dateArr: [],
      hasEdit: false,
      currStatus: '0',
      formInfo: {},
      hasDefault: false,
    };
  },
  computed: {
    buttons() {
      const disabled = !this.rowSelectionMixin.selectedRowKeys.length;
      return [
        {
          key: 'add',
          type: 'primary',
          label: '发起价格变更',
          icon: 'plus',
        },
        {
          key: 'delete',
          label: '删除',
          icon: 'delete',
          authKey: 'price-button-delete',
          disabled,
        },
        {
          key: 'retweet',
          label: '转他人处理',
          icon: 'retweet',
          authKey: 'price-button-transfer',
          disabled,
        },
      ];
    },
  },
  created() {
    this.loadTableList();
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      if (to.query?.id) {
        vm.handleNumberClick(to.query);
      }
    });
  },
  methods: {
    rescurrStatus() {},
    intersection(a, b) {
      const s = new Set(b);
      return [...new Set(a)].filter((x) => s.has(x));
    },
    async getPriceDetail(priceId) {
      const result = await getPriceDetail(priceId);
      this.data = result?.data.data.nodeFlowCharts;
      this.logs = result?.data.data.logs;
      this.formData = result.data.data.priceChangeDetails;
      if (this.formData.length !== 0) {
        this.formData.forEach((item) => {
          this.keyArray.push(item.id);
        });
      }
      // this.keyArray = result?.data.data.selectKeys;
      this.formInfo = result?.data.data;
      const timeArray = [
        this.formInfo.startTime.substring(0, 7),
        this.formInfo.endTime.substring(0, 7),
      ];
      const timeArray2 = createMonthArray(timeArray);
      // console.log('this.formInfo: ', this.formInfo);
      if (this.formData.length !== 0) {
        const dateArr = Object.keys(
          JSON.parse(result?.data.data.priceChangeDetails[0].newPrice)
        );
        this.dateArr = this.intersection(dateArr, timeArray2);
        this.dateArr = this.dateArr.sort((a, b) => {
          return (
            parseInt(a.replace(/\D/g, ''), 7) -
            parseInt(b.replace(/\D/g, ''), 7)
          );
        });
      }

      if (result?.data.data.isCurrentProcessor) {
        this.hasEdit = true;
      } else if (
        !result?.data.data.isCurrentProcessor ||
        this.currStatus === '3'
      ) {
        this.hasEdit = false;
      }
      // if (this.currStatus === '1' || this.currStatus === '2') {

      // }
    },

    handleNumberClick(record) {
      let currentNode = PRICE_NODE[Number(record.nodeCode)];
      if (!currentNode) {
        this.$message.error('非有效节点，无法进入！');
        return;
      }
      this.currStatus = record.currStatus;
      if (this.currStatus === '1') {
        this.hasDefault = false;
        this.currentNode = PRICE_NODE[Number(1)];
      } else {
        this.hasDefault = true;
        this.currentNode = PRICE_NODE[Number(record.nodeCode)];
      }
      this.currentComponent = `Drawer${this.currentNode.key}`;
      this.processId = record.processId;
      this.priceId = record.id;
      this.visibleDrawer = true;
      this.getPriceDetail({ priceId: record.id });
    },
    getSearchForm() {
      const form = this.$refs['search-form']?.form || {};
      const copyForm = JSON.parse(JSON.stringify(form));
      if (copyForm.startTime === null && copyForm.endTime !== null) {
        copyForm.startTime = copyForm.endTime;
      } else if (copyForm.endTime === null && copyForm.startTime !== null) {
        copyForm.endTime = copyForm.startTime;
      }
      copyForm.startTime =
        copyForm.startTime === undefined || copyForm.startTime === null
          ? null
          : monent(copyForm.startTime).format('YYYY-MM-DD');
      copyForm.endTime =
        copyForm.endTime === undefined || copyForm.startTime === null
          ? null
          : monent(copyForm.endTime).format('YYYY-MM-DD');
      const page = {
        current: this.paginationMixin.current,
        pageSize: this.paginationMixin.pageSize,
        asc: this.asc,
        column: this.columnKey,
      };
      return { ...copyForm, ...page };
    },
    async loadTableList() {
      this.loading = true;
      const form = this.getSearchForm();
      const result = await postPriceList(form).finally(
        () => (this.loading = false)
      );
      this.paginationMixin.total = result.data.data?.total;

      this.dataSource = result.data.data?.records;
      this.dataSource.forEach((item) => {
        item.timeChange =
          item.startTime.substring(0, 7).replace(/-/, '') +
          '~' +
          item.endTime.substring(0, 7).replace(/-/, '');
      });
    },
    // async pageChangeTable() {
    //   this.loading = true;
    //   const result = await postPriceList({
    //     current: this.paginationMixin.current,
    //   }).finally(() => (this.loading = false));
    //   this.paginationMixin.total = result.data.data?.total;

    //   this.dataSource = result.data.data?.records;
    //   this.dataSource.forEach((item) => {
    //     item.timeChange =
    //       item.startTime.substring(0, 7).replace(/-/, '') +
    //       '~' +
    //       item.endTime.substring(0, 7).replace(/-/, '');
    //   });
    // },
    handleTableChange(page, filters, sorter, { currentDataSource }) {
      this.asc = sorter.order === 'ascend' ? true : false;
      this.columnKey = sorter.columnKey;
      this.paginationMixin = page;
      this.loadTableList();
    },
    handleButtonClick(key) {
      // this.currentComponent = 'DrawerSalesDirecorAudit';
      // this.visibleDrawer = true;
      const fn = `${key}Callback`;
      this[fn] && this[fn]();
    },
    changeCurrstatus(val) {
      this.currStatus = val;
    },
    addCallback() {
      this.currStatus = '0';
      this.currentComponent = 'DrawerPriceStart';
      this.hasDefault = true;
      this.formData = [];
      this.dateArr = [];
      this.hasEdit = true;
      // this.currentNode = PLAN_NODE[1];
      // this.planId = undefined;
      // this.detail = {};
      this.visibleDrawer = true;
    },
    async retweetCallback() {
      const selectedInfos = this.rowSelectionMixin.selectedRows
        .filter((item) => item.currStatus === '2')
        .map((item, i) => {
          return {
            serialNumber: item.serialNumber,
            currentUserId: item.handleUserId,
            planId: item.id,
            handleUserName: item.handleUserName,
            name: [],
          };
        });
      if (!selectedInfos.length) {
        this.$message.info(
          `仅可转他人处理审批中的数据，现有 ${selectedInfos.length} 条！`
        );
        return;
      }
      try {
        await this.$confirm(
          `仅可转他人处理审批中的数据，共 ${selectedInfos.length} 条，是否确认？`
        );

        this.visibleModal = true;
        this.selectedInfos = selectedInfos;
      } catch (error) {
        // console.log('error: ', error);
      }
    },

    async deleteCallback() {
      const ids = this.rowSelectionMixin.selectedRowKeys || [];
      if (!ids.length) {
        this.$message.info('请先选择数据！');
        return;
      }
      try {
        await this.$confirm(`该操作将删除 ${ids.length} 条数据，是否确认？`);
        const checkedRows = this.dataSource.reduce((pre, cur) => {
          if (ids.includes(cur.id)) {
            pre.push(cur);
          }
          return pre;
        }, []);
        const isValid = checkedRows.some((item) => item.currStatus !== '1');
        if (isValid) {
          this.$message.error('只可删除草稿状态的价格变更！');
          return;
        }

        await postDeletePriceChange(this.rowSelectionMixin.selectedRowKeys);
        this.$message.success('删除成功');
        this.rowSelectionMixin.selectedRowKeys = [];
        this.loadTableList();
      } catch (error) {
        // console.log('error: ', error);
      }
    },
  },
};
</script>



